// ============================================================================
// Task 实体定义
// ============================================================================

import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index
} from 'typeorm'
import { TaskType, TaskStatus, ScrapeTask } from '../../../shared/types'
import { Account } from './account.entity'
import { TaskLog } from './task-log.entity'
import { JsonTransformer, ScheduledTaskParamsTransformer } from '../transformers/json.transformer'

/**
 * 任务实体
 */
@Entity('tasks')
@Index(['type'])
@Index(['status'])
@Index(['accountId'])
@Index(['createdAt'])
export class Task {
  @PrimaryColumn({ type: 'varchar' })
  id: string

  @Column('varchar')
  type: string

  @Column({
    type: 'text',
    transformer: new ScheduledTaskParamsTransformer()
  })
  params: any

  @Column('varchar')
  status: string

  @Column({ name: 'account_id', type: 'varchar' })
  accountId: string

  @Column({ name: 'started_at', type: 'datetime', nullable: true })
  startedAt?: Date

  @Column({ name: 'completed_at', type: 'datetime', nullable: true })
  completedAt?: Date

  @Column({ 
    type: 'text', 
    nullable: true, 
    transformer: new JsonTransformer() 
  })
  progress?: any

  @Column({ 
    type: 'text', 
    nullable: true, 
    transformer: new JsonTransformer() 
  })
  result?: any

  @Column({ type: 'integer', default: 0 })
  priority: number

  @Column({ name: 'retry_count', type: 'integer', default: 0, nullable: true })
  retryCount: number

  @Column({ name: 'max_retries', type: 'integer', default: 3, nullable: true })
  maxRetries: number

  @Column({ 
    type: 'text', 
    nullable: true, 
    transformer: new JsonTransformer() 
  })
  tags?: string[]

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date

  // 关系
  @ManyToOne(() => Account, account => account.tasks, { 
    onDelete: 'CASCADE',
    eager: false 
  })
  @JoinColumn({ name: 'account_id' })
  account: Account

  @OneToMany(() => TaskLog, log => log.task, { 
    cascade: true,
    eager: false 
  })
  logs: TaskLog[]

  /**
   * 检查任务是否为定时任务
   */
  isScheduledTask(): boolean {
    return this.type === 'scheduled'
  }

  /**
   * 检查任务是否已完成
   */
  isCompleted(): boolean {
    return this.status === 'completed' || this.status === 'failed'
  }

  /**
   * 检查任务是否正在运行
   */
  isRunning(): boolean {
    return this.status === 'running' || this.status === 'pending'
  }

  /**
   * 获取任务持续时间（毫秒）
   */
  getDuration(): number | null {
    if (!this.startedAt || !this.completedAt) {
      return null
    }
    const completedTime = this.completedAt instanceof Date ? this.completedAt.getTime() : new Date(this.completedAt).getTime()
    const startedTime = this.startedAt instanceof Date ? this.startedAt.getTime() : new Date(this.startedAt).getTime()
    return completedTime - startedTime
  }

  /**
   * 更新任务状态
   */
  updateStatus(status: string, progress?: any): void {
    this.status = status
    if (progress !== undefined) {
      this.progress = progress
    }
    
    if (status === 'running' && !this.startedAt) {
      this.startedAt = new Date()
    }
    
    if ((status === 'completed' || status === 'failed') && !this.completedAt) {
      this.completedAt = new Date()
    }
  }

  /**
   * 增加重试次数
   */
  incrementRetryCount(): void {
    this.retryCount = (this.retryCount || 0) + 1
  }

  /**
   * 检查是否可以重试
   */
  canRetry(): boolean {
    return (this.retryCount || 0) < (this.maxRetries || 3)
  }

  /**
   * 转换为 ScrapeTask 格式（向后兼容）
   */
  toScrapeTask(): ScrapeTask {
    return {
      id: this.id,
      type: this.type as TaskType,
      params: this.params,
      status: this.status as TaskStatus,
      accountId: this.accountId,
      createdAt: this.createdAt,
      startedAt: this.startedAt,
      completedAt: this.completedAt,
      progress: this.progress,
      result: this.result,
      priority: this.priority,
      retryCount: this.retryCount || 0,
      maxRetries: this.maxRetries || 3,
      tags: this.tags,
      logs: this.logs?.map(log => log.toTaskLogEntry()) || []
    }
  }

  /**
   * 从 ScrapeTask 创建任务实体
   */
  static fromScrapeTask(scrapeTask: any): Task {
    const task = new Task()
    task.id = scrapeTask.id
    task.type = scrapeTask.type
    task.params = scrapeTask.params
    task.status = scrapeTask.status
    task.accountId = scrapeTask.accountId
    task.startedAt = scrapeTask.startedAt
    task.completedAt = scrapeTask.completedAt
    task.progress = scrapeTask.progress
    task.result = scrapeTask.result
    task.priority = scrapeTask.priority || 0
    task.retryCount = scrapeTask.retryCount || 0
    task.maxRetries = scrapeTask.maxRetries || 3
    task.tags = scrapeTask.tags
    return task
  }
}
